// kquick.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "kquick.h"

#include "kqfuncs.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CkquickApp

BEGIN_MESSAGE_MAP(CkquickApp, CWinApp)
	ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()

// CkquickApp construction

CkquickApp::CkquickApp()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}


// The one and only CkquickApp object

CkquickApp theApp;

// CkquickApp initialization


BOOL CkquickApp::InitInstance()
{
	// InitCommonControlsEx() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);

	// Set this to include all the common control classes you want to use
	// in your application.
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinApp::InitInstance();

#ifdef _DEBUG
	MessageBox(NULL, L"Attach To Debug", L"kquick debug", 0);
#endif

	HANDLE eventFromKqdll = CreateEvent(NULL, FALSE, FALSE, L"kquickEvent");
	if (GetLastError() == ERROR_ALREADY_EXISTS) {
		CloseHandle(eventFromKqdll);
		return FALSE;
	}

	LoadKqDLL();

	char hk_str[20] = {0};
	GetPrivateProfileStringA("SETTING", "HOTKEY", "ALT+Q", hk_str, 15, "./kquick.ini");
	for (int i = 0; i < 20; ++i) {
		hk_str[i] = toupper(hk_str[i]);
	}

	char vkkey;
	char hotkey;
	if (ParseHotkey(hk_str, vkkey, hotkey) == FALSE) {
		AfxMessageBox(L"Reading Hotkey Config Failed");
		return FALSE;
	}

	HANDLE hThread = ::CreateThread(NULL, 0, HandleThread, 0, 0, 0);
	if (InstallHook(vkkey, hotkey) == false) {
		AfxMessageBox(L"failed");
		CloseHandle(eventFromKqdll);
		return FALSE;
	}

	WaitForSingleObject(hThread, INFINITE);
	UninstallHook();
	CloseHandle(hThread);

	UnloadKqDLL();
	CloseHandle(eventFromKqdll);

	return FALSE;
}
